/* 库存监控报表
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\Report\InventoryMonitoringReport\index.tsx
 * @Date: 2021-12-14 09:58:20
 * @LastEditTime: 2021-12-14 09:58:21
 */
import React from 'react'
import {
  BaseListPage,
  http,
  IBaseListPageState,
  IBaseListPageProps,
  uaaApp,
  UdMonthPicker,
  UdModal,
  IUdFormItem,
} from '@/lib'

import { Button, Spin, Tooltip, TreeSelect } from 'antd'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import apis from '@/apis'
import quotaApis from '@/apis/AboutQuota'
import { downBlobFile } from '@/utils/methods'
import dayjs from 'dayjs'
import { InnerTable } from './components/InnerTable'
import moment from 'moment'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import _ from 'lodash'
const { TreeNode } = TreeSelect
const exportBtn = 'InventoryMonitoringReport_export' //导出
export default class InventoryMonitoringReportList extends BaseListPage<IProps, IState> {
  protected useConditionsField = true
  private spanUI: any = {
    color: '#00c1de',
    fontWeight: 'bold',
    cursor: 'pointer',
    paddingRight: '10px',
    padding: '10px 0',
  }
  // 隐藏掉头曲二曲
  // public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  // public brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  public brandList = udMainStore.brandList
  constructor(props) {
    super(props)
    this.state = {
      title: '库存监控报表',
      queryApi: params => {
        let {
          conditions: { inventoryMonth },
        } = params
        inventoryMonth && (params.conditions.inventoryMonth = dayjs(inventoryMonth).format('YYYY-MM-DD HH:mm:ss'))
        return http.post(quotaApis.queryDealerInventoryControlPage, params)
      },
      method: 'POST',
      rowKey: (record, index) => index + '',
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          initialValue: this.brandList[0].value,
          render: (
            <UdSelect
              showSearch
              allowClear={false}
              options={this.brandList}
              onChange={value => {
                this.changeBrandCode(value)
              }}
            />
          ),
        },
        {
          label: '统计月份',
          id: 'inventoryMonth',
          initialValue: moment(),
          render: () => (
            <UdMonthPicker
              allowClear={false}
              onChange={() => { }}
              placeholder="请选择年度月份"
              style={{ width: '100%' }}
              className={'ext'}
            />
          ),
        },
        {
          label: '所属组织',
          id: 'belongAreaCode',
          render: () => (
            <TreeSelect showSearch treeNodeFilterProp="title">
              {this.mapTree(this.state.treeDataList)}
            </TreeSelect>
          ),
        },
        {
          label: '物料分类',
          id: 'groupCode',
          render: () => {
            return <UdSelect showSearch options={this.state.prodBarCodeList} />
          },
        },
        { label: '经销商编码', id: 'dealerCode' },
        { label: '经销商名称', id: 'dealerName' },
      ],
      columns: [
        ['序号', 'id', (text, record, index) => index + 1, { minWidth: '30px' }],
        { title: '品牌公司', dataIndex: 'brandName', minWidth: '60px' },
        { title: '所属大区', dataIndex: 'assessAreaName', minWidth: '60px' },
        { title: '所属组织', dataIndex: 'belongAreaName', minWidth: '60px' },
        { title: '经销商编码', dataIndex: 'dealerCode', minWidth: '80px' },
        { title: '经销商名称', dataIndex: 'dealerName', minWidth: '180px' },
        { title: '经销商地址', dataIndex: 'address', minWidth: '180px' },
        { title: '物料分类编号', dataIndex: 'groupCode', minWidth: '75px' },
        { title: '物料分类名称', dataIndex: 'groupName', minWidth: '140px' },
        {
          title: '盘点物料编码',
          dataIndex: 'prodBarcode',
          width: 180,
          render: (text, record) => {
            return (
              <Tooltip title={record.prodBarcode}>
                <div
                  style={{
                    width: '180px',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                    cursor: 'pointer',
                  }}
                >
                  {record.prodBarcode}
                </div>
              </Tooltip>
            )
          },
        },
        {
          title: '统计月份',
          dataIndex: 'inventoryMonth',
          minWidth: '70px',
          render: (text, record) => {
            return text ? dayjs(text).format('YYYY-MM') : ''
          },
        },
        {
          title: '月均动销/件',
          dataIndex: 'nowMove',
          minWidth: '70px',
          render: (text, record) => {
            return record.nowMove ? (
              <span
                onClick={() => {
                  this.showInnerTableModal(record)
                }}
                style={this.spanUI}
              >
                {record.nowMove}
              </span>
            ) : (
              record.nowMove || ''
            )
          },
        },
        { title: '安全库存', dataIndex: 'stockSafety', minWidth: '65px' },
        { title: '期末库存', dataIndex: 'nowRealStock', minWidth: '65px' },
        { title: '库存差值', dataIndex: 'stockDifference', minWidth: '65px' },
      ],
      leftBtns: [
        uaaApp.canUse(exportBtn) && (
          <Button type="primary" onClick={this.handExportTableData}>
            导出
          </Button>
        ),
      ],
      uploading: false,
      downloading: false,
      tableProps: {
        rowSelection: null,
      },
      prodBarCodeList: [],
      treeDataList: [],
    }
  }

  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '请求中，请稍后...'}
      >
        {super.render()}
      </Spin>
    )
  }

  componentDidMount() {
    super.componentDidMount()
    this.changeBrandCode(this.filterForm.getFieldValue('brandCode'))
  }

  protected filterReset = (form: WrappedFormUtils) => {
    let defaultValues: any = {}
    _.forEach(this.state.conditions, (item: IUdFormItem) => {
      if (item.initialValue) {
        let key = _.isArray(item.id) ? item.id.join('|') : item.id
        defaultValues[key] = item.initialValue
      }
    })
    var conditions = _.merge({}, this.defaultQueryParams.conditions, defaultValues)
    this.handleSearch(conditions)
    this.changeBrandCode(this.brandList[0].value)
  }

  private getProdBarList = (value: any) => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        return prodBarCodeList
      })
  }

  private changeBrandCode = (value: any) => {
    this.filterForm.setFieldsValue({ groupCode: undefined, belongAreaCode: undefined }, () => {
      this.setState({ prodBarCodeList: [], treeDataList: [] }, () => {
        Promise.allSettled([this.getProdBarList(value), this.getAreaList(value)]).then((res: any) => {
          this.setState({
            prodBarCodeList: res[0]?.value || [],
            treeDataList: res[1]?.value || [],
          })
        })
      })
    })
  }

  private getAreaList = (value: any) => {
    return http
      .get(apis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  private showInnerTableModal = record => {
    UdModal.open({
      centered: true,
      title: `${record.brandName}-${record.dealerName}(动销数)`,
      width: '60%',
      content: <InnerTable record={record} />,
      footer: null,
    })
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }

  private handExportTableData = () => {
    this.setState({ downloading: true })
    let params = this.filterForm.getFieldsValue()
    let { brandCode } = this.filterForm.getFieldsValue()
    let brandName = this.brandList.find(item => {
      return item.value === brandCode
    })?.title
    let { inventoryMonth } = params
    inventoryMonth && (params.inventoryMonth = dayjs(inventoryMonth).format('YYYY-MM-DD HH:mm:ss'))
    http
      .post(quotaApis.downloadDealerInventoryControlExcel, params, {
        responseType: 'arraybuffer',
      })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, `${dayjs(inventoryMonth).format('YYYY-MM')}-${brandName}-经销商库存监控报表`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }
}

interface IState extends IBaseListPageState {
  uploading: boolean
  downloading: boolean
  treeDataList: any[]
  prodBarCodeList: any[]
  loading?: boolean
}

interface IProps extends IBaseListPageProps { }
